import { type CrudConfig, type FormSection } from '@/components';
import DICT_CONSTANTS from '@/constants/dictConstants';
import urlConstants from '@/constants/urlConstants';
import type { ProColumns } from '@ant-design/pro-components';
import { Tag } from 'antd';

// 用户数据类型
export interface UserRecord {
  paramIndex: number;
  userId: string;
  userName: string;
  orgNo: string;
  roleIds: string;
  positionIds: string;
  gender: string;
  language: string;
  level: string;
  updateUser: string;
  updateTime: string;
}

// 数据处理函数
const getRequestData = (postData: any, type: string, rowData: any): object => {
  switch (type) {
    case 'create':
    case 'edit':
      return {
        ...postData.formData,
        language: postData.formData.language?.join(','),
        positionIds: postData.formData.positionIds?.join(','),
        roleIds: postData.formData.roleIds?.join(','),
      };
    default:
      return { ...postData };
  }
};

// 统一的页面配置函数 - 接收 translate 函数作为参数
export const getPageConfig = (translate: (prefix: string, key: string) => string) => {
  const t = (key: string) => translate('systemManage', key);

  return {
    // CRUD配置
    crudConfig: {
      endpoints: {
        list: urlConstants.USER_MANAGEMENT.LIST,
        create: urlConstants.USER_MANAGEMENT.CREATE,
        update: urlConstants.USER_MANAGEMENT.EDIT,
        delete: urlConstants.USER_MANAGEMENT.DELETE,
        detail: urlConstants.USER_MANAGEMENT.LIST,
      },
      callbacks: {
        beforeCreate: async (data: any) => getRequestData(data, 'create', null),
        beforeUpdate: async (data: any) => getRequestData(data, 'edit', null),
        afterCreate: async (response: any) => console.log('用户创建成功:', response),
        afterUpdate: async (response: any) => console.log('用户更新成功:', response),
        afterDelete: async (response: any, id: string) => console.log('用户删除成功:', id),
        onError: (error: any, operation: string) => console.error(`用户操作 ${operation} 失败:`, error),
      },
    } as CrudConfig,

    // 搜索字段配置
    searchFields: [
      {
        name: 'positionIds',
        label: t('positionIds'),
        type: 'input' as const,
      },
      {
        name: 'userId',
        label: t('userId'),
        type: 'input' as const,
      },
      {
        name: 'userName',
        label: t('userName'),
        type: 'input' as const,
      },
    ],

    // 表格列配置
    columns: [
      {
        title: t('serialNumber'),
        dataIndex: 'paramIndex',
        key: 'paramIndex',
        width: 80,
        fixed: 'left',
      },
      {
        title: t('userId'),
        dataIndex: 'userId',
        key: 'userId',
        width: 120,
        copyable: true,
      },
      {
        title: t('userName'),
        dataIndex: 'userName',
        key: 'userName',
        width: 120,
        ellipsis: true,
        render: (text: string) => <div style={{ wordWrap: 'break-word', whiteSpace: 'normal' }}>{text}</div>,
      },
      {
        title: t('orgNo'),
        dataIndex: 'orgNo',
        key: 'orgNo',
        width: 180,
        render: (text: string) => {
          const labelTypeMap = DICT_CONSTANTS.LABEL_TYPE || {};
          const displayText = labelTypeMap[text as keyof typeof labelTypeMap] || text;
          return <Tag>{String(displayText)}</Tag>;
        },
      },
      {
        title: t('roleIds'),
        dataIndex: 'roleIds',
        key: 'roleIds',
        width: 120,
        render: (text: string) => {
          const labelSourceMap = DICT_CONSTANTS.LABEL_SOURCE || {};
          const displayText = labelSourceMap[text as keyof typeof labelSourceMap] || text;
          return <Tag>{String(displayText)}</Tag>;
        },
      },
      {
        title: t('positionIds'),
        dataIndex: 'positionIds',
        key: 'positionIds',
        width: 150,
        render: (text: string) => {
          const labelAttributeMap = DICT_CONSTANTS.LABEL_ATTRIBUTE || {};
          const displayText = labelAttributeMap[text as keyof typeof labelAttributeMap] || text;
          return <Tag>{String(displayText)}</Tag>;
        },
      },
      {
        title: t('gender'),
        dataIndex: 'gender',
        key: 'gender',
        width: 100,
        render: (text: string) => {
          const paramStatusMap = DICT_CONSTANTS.PARAM_STATUS || {};
          const displayText = paramStatusMap[text as keyof typeof paramStatusMap] || text;
          return <Tag>{String(displayText)}</Tag>;
        },
      },
      {
        title: t('language'),
        dataIndex: 'language',
        key: 'language',
        width: 100,
        render: (text: string) => {
          const paramStatusMap = DICT_CONSTANTS.PARAM_STATUS || {};
          const displayText = paramStatusMap[text as keyof typeof paramStatusMap] || text;
          return <Tag>{String(displayText)}</Tag>;
        },
      },
      {
        title: t('level'),
        dataIndex: 'level',
        key: 'level',
        width: 100,
        render: (text: string) => {
          const paramStatusMap = DICT_CONSTANTS.PARAM_STATUS || {};
          const displayText = paramStatusMap[text as keyof typeof paramStatusMap] || text;
          return <Tag>{String(displayText)}</Tag>;
        },
      },
      {
        title: t('updateUser'),
        dataIndex: 'updateUser',
        key: 'updateUser',
        width: 120,
        ellipsis: true,
      },
      {
        title: t('updateTime'),
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 160,
        valueType: 'dateTime',
        sorter: true,
      },
    ] as ProColumns<UserRecord>[],

    // 表单字段配置
    formFields: [
      {
        title: t('baseInfo'),
        fields: [
          {
            name: 'userId',
            label: t('userId'),
            type: 'input' as const,
            rules: [{ required: true, message: t('userIdRequired') }],
          },
          {
            name: 'userName',
            label: t('userName'),
            type: 'input' as const,
            rules: [{ required: true, message: t('userNameRequired') }],
          },
          {
            name: 'password',
            label: t('password'),
            type: 'input' as const,
            rules: [{ required: true, message: t('passwordRequired') }],
          },
          {
            name: 'orgNo',
            label: t('orgNo'),
            type: 'select' as const,
            options: Object.entries(DICT_CONSTANTS.LABEL_TYPE || {}).map(([key, value]) => ({
              label: String(value),
              value: key,
            })),
            rules: [{ required: true, message: t('orgNoRequired') }],
          },
          {
            name: 'roleIds',
            label: t('roleIds'),
            type: 'select' as const,
            mode: 'multiple',
            options: Object.entries(DICT_CONSTANTS.LABEL_SOURCE || {}).map(([key, value]) => ({
              label: String(value),
              value: key,
            })),
            rules: [{ required: true, message: t('roleIdsRequired') }],
          },
          {
            name: 'positionIds',
            label: t('positionIds'),
            type: 'select' as const,
            mode: 'multiple',
            options: Object.entries(DICT_CONSTANTS.LABEL_ATTRIBUTE || {}).map(([key, value]) => ({
              label: String(value),
              value: key,
            })),
            rules: [{ required: true, message: t('positionIdsRequired') }],
          },
          {
            type: 'select' as const,
            name: 'subPositionPermission',
            label: t('subPositionPermission'),
            options: DICT_CONSTANTS.PARAM_STATUS,
            rules: [{ required: true, message: t('subPositionPermissionRequired') }],
          },
        ],
      },
      {
        title: t('contactInfo'),
        fields: [
          {
            name: 'gender',
            label: t('gender'),
            type: 'select' as const,
            options: Object.entries(DICT_CONSTANTS.PARAM_STATUS || {}).map(([key, value]) => ({
              label: String(value),
              value: key,
            })),
            rules: [{ required: true, message: t('genderRequired') }],
          },
          {
            name: 'language',
            label: t('language'),
            type: 'select' as const,
            mode: 'multiple',
            options: Object.entries(DICT_CONSTANTS.PARAM_STATUS || {}).map(([key, value]) => ({
              label: String(value),
              value: key,
            })),
            rules: [{ required: true, message: t('languageRequired') }],
          },
          {
            name: 'level',
            label: t('level'),
            type: 'select' as const,
            options: Object.entries(DICT_CONSTANTS.PARAM_STATUS || {}).map(([key, value]) => ({
              label: String(value),
              value: key,
            })),
            rules: [{ required: true, message: t('levelRequired') }],
          },
        ],
      },
    ] as FormSection[],

    // 字典枚举配置
    dictEnum: {
      language: DICT_CONSTANTS.DICT_ENUM_MAP.language,
      roleIds: DICT_CONSTANTS.DICT_ENUM_MAP.roleIds,
      positionIds: DICT_CONSTANTS.DICT_ENUM_MAP.positionIds,
    },
  };
};
